<template>
    <el-container class="base_user">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="queryData"
                                title="可模糊搜索账户名、员工"
                                @event="handleHeaderEvent">
                    <template slot="right_search">
                        <el-select v-model="queryData.role_sid" clearable placeholder="请选择角色" @change="getList(true)"
                                   style="width: 150px;margin-right: 5px;">
                            <el-option label="全部角色" value="" />
                            <el-option v-for="(item, index) in roleOptions" :key="index"
                                       :label="item.name" :value="item.sid" />
                        </el-select>
                        <tree-select class="search" v-bind.sync="groupTreeOption"
                                     style="width: 150px;margin-right: 5px;" @input="inputTreeSelect" />
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import sysUserApi from "@common/api/system/sysUserApi";
import sysRoleApi from "@common/api/system/sysRoleApi";
import fileApi from "@common/api/fileApi";
import poiApi from "@common/api/poiApi";
import provide from "@common/mixins/provide";
import UserForm from "../dialog/user/UserForm";
import ResetPwdForm from "../dialog/user/ResetPwdForm";
import DataAuth from "../dialog/user/DataAuth";

export default {
    extends: provide,
    name: "SysUser",
    data() {
        let $this = this;
        return {
            queryData: {
                role_sid: '',
                group_sid: 'all',
            },
            groupTreeOption: {
                defaultExpandLevel: 1,
                clearable: false,
                options: [],
            },
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            $this.getList();
                        },
                    },
                    {
                        id: "add",
                        type: 'primary',
                        icon: "fa fa-plus",
                        show: true,
                        permission: 'system:user:save',
                        method: () => {
                            $this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "edit",
                        type: 'success',
                        icon: "fa fa-pencil",
                        show: true,
                        permission: 'system:user:save',
                        method: () => {
                            $this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "del",
                        type: 'danger',
                        icon: "fa fa-trash-o",
                        show: true,
                        permission: 'system:user:delete',
                        method: () => {
                            $this.delUser(null, 'batch');
                        },
                    },
                    // {
                    //     id: "export",
                    //     label: '导出',
                    //     type: 'info',
                    //     icon: "el-icon-download",
                    //     show: true,
                    //     permission: 'export_sys_user',
                    //     method: () => {
                    //         $this.exportExcel();
                    //     },
                    // },
                    // {
                    //     id: "user_print",
                    //     label: '打印',
                    //     type: 'warning',
                    //     icon: "el-icon-printer",
                    //     show: true,
                    //     permission: 'print_sys_user',
                    //     method: () => {
                    //         $this.printTable();
                    //     },
                    // },
                ],
                toolbar_filter: [
                ],
            },
            fileApiUrl: fileApi.url,
            dataList: [],
            tableOptions: {
                ref: "UserTable",
                container: ".base_user",
                multiSelect: true,
                checkboxConfig: {
                    visibleMethod({ row }) {
                        return row.sid !== 'admin';
                    },
                    checkMethod({ row }) {
                        return row.sid !== 'admin';
                    },
                },
                columns: [
                    {
                        label: "头像",
                        prop: "head_pic",
                        align: "center",
                        width: 100,
                        cellRender: {
                            name: 'TableImage',
                        },
                    },
                    {
                        label: "账户名",
                        prop: "login_id",
                        align: "center",
                    },
                    {
                        label: "角色",
                        prop: "role_name",
                        align: "center",
                    },
                    {
                        label: "员工姓名",
                        prop: "group_person_name",
                        align: "center",
                    },
                    {
                        label: "部门名称",
                        prop: "group_name",
                        align: "center",
                    },
                    {
                        label: "最近一次登录",
                        prop: "last_logined_date",
                        align: "center",
                    },
                ],
                operates: {
                    list: [
                        {
                            id: "info",
                            icon: "el-icon-key",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "重置密码",
                            },
                            permission: 'system:user:resetPwd',
                            method: (index, row) => {
                                $this.updatePassword(row);
                            },
                        },
                        {
                            id: "preview",
                            icon: "fa fa-qrcode",
                            type: "primary",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "二维码",
                            },
                            permission: 'system:user:qrcode',
                            method: (index, row) => {
                                $this.openPreviewDialog(row);
                            },
                        },
                        {
                            id: "info",
                            icon: "fa fa-pencil",
                            type: "success",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "编辑",
                            },
                            permission: 'system:user:save',
                            method: (index, row) => {
                                $this.openDialog(row, "edit");
                            },
                        },
                        {
                            id: "row",
                            icon: "fa fa-cogs",
                            type: "success",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "数据范围授权",
                            },
                            permission: 'system:user:dataAuth',
                            filter() {
                                return $this.global_setting.enable_data_auth === 1;
                            },
                            method: (index, row) => {
                                $this.openDataAuthDialog(row, 'row');
                            },
                        },
                        {
                            id: "field",
                            icon: "fa fa-cogs",
                            type: "success",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "数据字段授权",
                            },
                            permission: 'system:user:dataAuthField',
                            filter() {
                                return $this.global_setting.enable_data_auth_field === 1;
                            },
                            method: (index, row) => {
                                $this.openDataAuthDialog(row, 'field');
                            },
                        },
                        {
                            id: "info",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "删除",
                            },
                            permission: 'system:user:delete',
                            filter(row) {
                                return row.sid !== 'admin';
                            },
                            method: (index, row) => {
                                $this.delUser(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
            selectionList: [],
            roleOptions: [],
        };
    },
    computed: {
        ...mapState([ 'userInfo', 'global_setting' ]),
    },
    mounted() {
        this.getList();
        this.getRoleList();
        this.initGroupTree();
    },
    methods: {
        handleHeaderEvent(event) {
            let $this = this;
            $this.queryData = $.extend({}, $this.queryData, event.searchForm);
            if (event.type === "search") {
                $this.getList(true);
            } else if (event.type === "refresh") {
                $this.getList(true);
            }
        },
        initGroupTree() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindSysGroupTree).then(result => {
                _this.groupTreeOption = $.extend({}, _this.groupTreeOption, {
                    options: [
                        {
                            id: 'all',
                            label: '全部部门',
                            children: _this.transferTreeData(result.data),
                        },
                    ],
                    value: _this.queryData.group_sid,
                });
            }).catch(() => {
            });
        },
        transferTreeData(datas) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(datas)) {
                list = datas.map(item => {
                    let obj = {};
                    obj.id = item.sid;
                    obj.label = item.name;
                    if (_this.$utils.isNotEmptyList(item.childrens)) {
                        obj.children = _this.transferTreeData(item.childrens);
                    }
                    return obj;
                });
            }
            return list;
        },
        getList(search) {
            let $this = this;
            $this.dataList = [];
            if (search) {
                $this.tableOptions = $this.resetTablePagination($this.tableOptions);
            }
            let queryData = $this.getQueryParams($this.tableOptions, $this.queryData);
            queryData.resource_client = '1';
            if ($this.$utils.isNotEmpty(queryData.group_sid) && queryData.group_sid === 'all') {
                delete queryData.group_sid;
            }
            sysUserApi.findSysUsers(queryData, (result) => {
                $this.dataList = result.data || [];
                $this.tableOptions = $this.setTableTotal($this.tableOptions, result);
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        inputTreeSelect(val) {
            const _this = this;
            if (val && val !== 'all') {
                _this.queryData.dept_sid = val;
            } else {
                delete _this.queryData.dept_sid;
            }
            _this.getList(true);
        },
        //获取角色列表
        getRoleList() {
            let $this = this;
            let queryData = { dr: 0, nopage: "1", with_resource: '1' };
            $this.roleOptions = [];
            sysRoleApi.findSysRoles(queryData, (result) => {
                if (result.data) {
                    $this.roleOptions = result.data.map((item) => {
                        return { sid: item.sid, name: item.name, resource_list: item.resource_list };
                    });
                }
            });
        },
        updatePassword(row) {
            const _this = this;
            _this.$dialog({
                title: '重置密码',
                width: '500px',
                component: {
                    value: ResetPwdForm,
                    props: {
                        row,
                    },
                },
                confirmed() {
                    _this.getList(true);
                },
            });
        },
        //新增/编辑
        openDialog(row, type) {
            const _this = this;
            let title = type === "add" ? "创建" : "编辑";
            if (!row) {
                if (type === 'add') {
                    row = {};
                }
                if (type === 'edit') {
                    if (!_this.checkSelection(_this.selectionList)) {
                        return;
                    }
                    row = $.extend({}, _this.selectionList[0]);
                }
            }
            _this.$dialog({
                title,
                width: '800px',
                component: {
                    value: UserForm,
                    props: {
                        row,
                    },
                },
                confirmed() {
                    _this.getList(true);
                    _this.$bus.$emit('updateSystemDashboard');
                },
            });
        },
        //删除
        delUser(row, type) {
            let $this = this;
            let sids = [];
            if (type === "batch") {
                if ($this.selectionList.length === 0) {
                    $this.$message.error("请选中一条数据");
                    return;
                } else {
                    sids = $this.selectionList.map((item) => item.sid);
                }
            } else {
                sids.push(row.sid);
            }
            $this.confirmDel(sids);
        },
        confirmDel(sids) {
            let $this = this;
            $this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                sysUserApi.batchDelSysUser({ sids }, () => {
                    $this.getList();
                    $this.$message.success("删除成功");
                    $this.$bus.$emit('updateSystemDashboard');
                });
            }).catch(() => {
            });
        },
        //导出
        exportExcel() {
            let queryData = $.extend({}, this.queryData);
            //Excel通用导出
            let title_field = [
                { name: "序号", key: "_index", width: 10 },
                { name: "头像", key: "head_pic", type: 2, width: 30, height: 60 },
                { name: "用户名", key: "login_id", width: 20 },
                { name: "角色", key: "role_name", width: 20 },
                { name: "姓名", key: "name", width: 20 },
                { name: "部门", key: "group_name", width: 20 },
                { name: "最近一次登录", key: "last_logined_date", width: 20 },
                { name: "创建时间", key: "create_date", width: 20 },
                { name: "状态", key: "dr" },
            ];
            let convert = {
                dr: [
                    { name: "有效", value: 0 },
                    { name: "无效", value: 1 },
                ],
            };
            poiApi.exportExcel(
                title_field,
                this.$api.API_FindSysUsers,
                queryData,
                "账户管理",
                convert
            );
            //Excel模板导出
            // let pic_field = 'head_pic';
            // poiApi.exportExcelTemplate(sysUserApi.excelExportTemplateName, this.$api.API_FindSysUsers, queryData, '用户管理', convert, pic_field);
        },
        exportExcel2() {
            let queryData = {
                sid: "85be901b89e0484cb6bd4da1c4316c76",
            };
            poiApi.exportExcelTemplateCustom(
                "text2.xlsx",
                this.$api.API_GetSaleOrderBySid,
                queryData,
                "测试导出"
            );
        },
        printTable() {
            let title_field = [];
            for (let item of this.tableOptions.columns) {
                title_field.push({
                    name: item.label,
                    key: item.prop,
                    width: item.width,
                    formatter: item.formatter,
                });
            }
            var html = this.$XEUtils.jsonToTable(title_field, this.dataList, null); //数据转换table格式html
            let printConfig = {
                sheetName: "用户管理", //页眉名称
            };
            this.$XPrint({ ...printConfig, content: html });
        },
        // 打开预览打印弹框
        openPreviewDialog(row) {
            let $this = this;
            $this.$QRCode({
                width: '500px',
                data: [
                    {
                        sid: row.sid,
                        text: $this.$utils.getAccountSetSid() + ";sysuser;" + row.sid,
                        tip: '二维码的值格式是：账套号;sysuser;数据sid',
                    }
                ],
                pageStyle: {
                    justifyContent: 'center',
                },
                showDownload: true,
            });
        },
        openDataAuthDialog(row, type) {
            const _this = this;
            _this.$dialog({
                title: `${ row.login_id }-${ type === 'row' ? '数据范围授权' : '数据字段授权' }`,
                width: '800px',
                component: {
                    value: DataAuth,
                    props: {
                        authType: type,
                        row,
                    },
                },
            });
        },
    },
};
</script>

<style lang="less" rel="stylesheet/less" scoped>
.base_user {
    height: 100%;

    .top-card {
        height: 65px !important;
    }

    .buttons {
        margin: 0 0 10px 0;
    }

    .head {
        /deep/ .el-upload--picture-card {
            display: none;
        }
    }

    .uploadPicture {
        /deep/ .el-upload--picture-card {
            width: 148px;
            height: 148px;
            line-height: 146px;
            margin-right: 60px;
        }
    }
}
</style>
